<script lang="ts" setup>
import { useUserStore } from "@/MyStore/Store";
import { ref } from "vue";
import {
  Document,
  Menu as IconMenu,
  Location,
  Setting,
} from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from "element-plus";
import router from "@/router";
const handleOpen = (key: string, keyPath: string[]) => {
  // console.log(key, keyPath)
};
const handleClose = (key: string, keyPath: string[]) => {
  // console.log(key, keyPath)
};


router.push('/Img')


const UserStore = useUserStore();

let UserName = ref(UserStore.UserName);

// 退出逻辑判断>
function checkout() {
  router.push("/");
}

const open = () => {
  ElMessageBox.confirm("你确定要退出?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      checkout();
      UserStore.logout();
      ElMessage({
        type: "success",
        message: "退出成功",
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "用户已取消",
      });
    });
};
// <退出逻辑判断

// 修改昵称>>
const changeNickname = () => {
  const maxLength = 20; // 假设我们设置的最大长度是20个字符

  ElMessageBox.prompt(
    "修改昵称", // 标题
    "请输入新的昵称", // 消息正文
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      inputValue: UserStore.UserName, // 可以设置输入框的初始值，例如当前用户的昵称
      inputType: "text", // 输入框类型，这里使用文本输入
      // 可以设置输入框的初始值，例如当前用户的昵称
      // inputValue: currentUser.nickname,
      // 正则表达式校验，这里简单示例为非空校验
      inputPattern: /\S/,
      inputErrorMessage: "昵称不能为空",
      inputValidator: (value) => {
        if (value.length <= maxLength) {
          return true; // 输入长度小于等于20，验证通过
        } else {
          return `昵称长度不能超过 ${maxLength} 个字符`; // 返回错误信息
        }
      },
    }
  )
    .then(({ value }) => {
      // 用户点击确定后，value 为输入框内的值
      // 这里调用实际修改昵称的函数，传入新的昵称
      UserStore.setUserName(value);
      updateNickname(value);
      ElMessage({
        type: "success",
        message: "昵称修改成功",
      });
    })
    .catch(() => {
      // 用户点击取消或输入不满足 inputPattern 时，会执行这里
      ElMessage({
        type: "info",
        message: "昵称修改已取消",
      });
    });
};

function updateUsername(id, name) {
  let data = { userid: id, username: name };
  fetch("/api/updateUsername", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify(data),
  })
    .then((response) => {
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      console.log(response);
      return response.json();
    })
    .then((resData) => {
      console.log("名称修改成功");
    })
    .catch((error) => {
      console.error("Error fetching data: ", error);
    });
}

// 这里是更新昵称函数的定义示例，接收新昵称作为参数
function updateNickname(newNickname) {
  // 这里是更新昵称函数的实现，执行昵称修改逻辑
  UserName.value = newNickname;
  console.log("新的昵称是：", newNickname);
  updateUsername(UserStore.UserId, newNickname);
}
// <<修改昵称

// 注销功能>>
function Onzhuxiao(id) {
  let data = { userid: id };

  fetch("/api/dead", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify(data),
  })
    .then((response) => {
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      console.log(response);
      return response.json();
    })
    .then((resData) => {
      console.log("注销成功");
    })
    .catch((error) => {
      console.error("Error fetching data: ", error);
    });
}

const zhuxiao = () => {
  // 弹出输入密码的对话框
  ElMessageBox.prompt("请输入密码以注销账号", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    // inputPattern: /^[A-Za-z0-9]{8}$/, // 这里可以设置密码的正则表达式规则
    // inputErrorMessage: '密码格式不正确'
  })
    .then(({ value }) => {
      // 用户点击确定后，验证密码
      if (value === UserStore.UserPwd) {
        // 密码正确，执行注销操作
        Onzhuxiao(UserStore.UserId);
        checkout();
        ElMessage({
          type: "success",
          message: "注销成功",
        });
        UserStore.logout(); // 执行注销用户的逻辑
      } else {
        // 密码错误，弹出提示消息
        ElMessage({
          type: "error",
          message: "密码错误，注销失败",
        });
      }
    })
    .catch(() => {
      // 用户点击取消，弹出提示消息
      ElMessage({
        type: "info",
        message: "用户已取消",
      });
    });
};
// <<注销功能
</script>

<template>
  <!--背景图片作为底板-->
  <div class="bg-image">
    <div class="common-layout">
      <el-container style="width: 100%; height: 100vh">
        <el-header class="header">
          <div class="headtitle">
            欢迎您！
            <el-icon size="22">
              <User />
            </el-icon>
            &nbsp;{{ UserName }}
          </div>
        </el-header>
        <el-container class="aside-main">
          <el-aside class="aside">
            <!-- 左侧菜单 -->
            <el-menu
              default-active="2"
              class="el-menu-vertical-demo"
              @open="handleOpen"
              @close="handleClose"
            >
              <!-- 书籍菜单 -->
              <el-sub-menu index="1" class="">
                <template #title>
                  <el-icon>
                    <Notebook />
                  </el-icon>
                  <span>书籍</span>
                </template>
                <router-link
                  to="/BookList"
                  style="text-decoration: none; color: inherit"
                >
                  <el-menu-item index="1-1">全部书籍</el-menu-item>
                </router-link>

                <router-link
                  to="/FindBook"
                  style="text-decoration: none; color: inherit"
                >
                  <el-menu-item index="1-2">查找</el-menu-item>
                </router-link>
              </el-sub-menu>
              <!-- 书籍菜单 -->

              <!-- 消息菜单 -->
              <!-- <el-menu-item index="2">
                <el-icon>
                  <Message />
                </el-icon>
                <span>消息</span>
              </el-menu-item> -->
              <!-- 消息菜单 -->

              <router-link
                to="/Recommon"
                style="text-decoration: none; color: inherit"
              >
                <el-menu-item index="3">
                  <el-icon>
                    <document />
                  </el-icon>
                  <span>分享与推荐</span>
                </el-menu-item>
              </router-link>

              <!-- 用户设置菜单 -->
              <el-sub-menu index="4" class="">
                <template #title>
                  <el-icon>
                    <setting />
                  </el-icon>
                  <span>用户设置</span>
                </template>
                <el-menu-item index="4-1" @click="changeNickname"
                  >昵称</el-menu-item
                >
                <el-menu-item index="4-2" @click="zhuxiao">注销</el-menu-item>
              </el-sub-menu>
              <!-- 用户设置菜单 -->

              <!-- 退出菜单 -->
              <el-menu-item index="5" @click="open">
                <el-icon>
                  <SwitchButton />
                </el-icon>
                <span>退出</span>
              </el-menu-item>
              <!-- 退出菜单 -->
            </el-menu>
            <!-- 左侧菜单 -->
          </el-aside>
          <el-main class="mainbody">
            <router-view></router-view>
          </el-main>
        </el-container>
      </el-container>
    </div>
  </div>
</template>




<style scoped>
.el-menu-item a {
  text-decoration: none !important;
  /* 移除下划线 */
  color: inherit !important;
  /* 保持颜色不变 */
}

.mainbody {
  background-color: #e9ecf6;
  height: 100%;
  width: 92%;
}

.aside {
  background-color: #ffffff;
  height: 100%;
  width: 15%;
  border-bottom-left-radius: 10px;
}

.header {
  height: 8%;
  background-color: #c7e7f9;
  border-top-left-radius: 10px;
  border-top-right-radius: 10px;
  align-content: center;
}

.headtitle {
  font-size: large;
  align-items: center;
  display: flex;
}

.common-layout {
  width: 100%;
  height: 100%;
  background-color: #ffffff;
  border-radius: 10px;
  opacity: 0.8;
  /* 80% 透明度 */
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.3);
  /* 4px垂直偏移，8px模糊半径，半透明黑色阴影 */
}
</style>